package org.linuxsogood.chapter2.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by m on 16/3/19.
 * properties 文件工具类
 */
public class PropsUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(PropsUtil.class);

    /**
     * 加载属性文件
     * @param fileName properties文件名
     * @return Properties
     */
    public static Properties loadProps(String fileName) {
        Properties properties = null;
        InputStream inputStream = null;
        try {
            inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            if (inputStream != null) {
                properties = new Properties();
                properties.load(inputStream);
            } else {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("file not found: fileName[{}]",fileName);
                }
            }
        } catch (Exception e) {
            //
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("加载properties文件异常:文件名:[{}]",fileName);
            }
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    //
                } finally {
                    inputStream = null;
                }
            }
        }
        return properties;
    }

    /**
     * 获取字符串类型属性(默认值为空字符串)
     * @param props
     * @param key
     * @return
     */
    public static String getString(Properties props, String key) {
        return getString(props, key, "");
    }

    /**
     * 获取字符串型值,可以指定默认值
     * @param props
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getString(Properties props, String key, String defaultValue) {
        String value = defaultValue;
        if (props.contains(key)) {
            value = props.getProperty(key);
        }
        return value;
    }

    public static int getInt(Properties prop, String key) {
        return getInt(prop, key, 0);
    }

    public static int getInt(Properties props, String key, int defaultValue) {
        int value = defaultValue;
        if (props.contains(key)) {
            value = CastUtils.castInt(props.get(key));
        }
        return value;
    }
}
